package com.mayikt.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.entity.SeckillEntity;
import com.mayikt.mapper.SeckillMapper;
import com.mayikt.service.OrderTokenService;
import com.mayikt.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderTokenServiceImpl extends BaseApiService implements OrderTokenService {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private TokenUtil tokenUtil;
    public BaseResponse<JSONObject> addSpikeToken(Long seckillId, Long tokenQuantity) {
        // 1.验证参数
        if (seckillId == null) {
            return setResultError("商品库存id不能为空!");
        }
        if (tokenQuantity == null) {
            return setResultError("token数量不能为空!");
        }
        SeckillEntity seckillEntity = seckillMapper.findBySeckillId(seckillId);
        if (seckillEntity == null) {
            return setResultError("商品信息不存在!");
        }
        // 2.使用多线程异步生产令牌
        createSeckillToken(seckillId, tokenQuantity);
        return setResultSuccess("令牌正在生成中.....");
    }


    private void createSeckillToken(Long seckillId, Long tokenQuantity) {
        tokenUtil.createListToken("seckill_", seckillId + "", tokenQuantity);
    }

}
